package com.kanas.webak.organization.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.inject.Singleton;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.kanas.framework.business.BusinessException;
import com.kanas.webak.organization.domain.Organization;
import com.kanas.webak.organization.repository.OrganizationRepository;

@Service("kanas.admin.service.organization")
@Singleton
public class OrganizationServiceImpl implements OrganizationService {
	@Autowired 
	private OrganizationRepository organizationRepository;

	public OrganizationRepository getOrganizationRepository() {
		return organizationRepository;
	}

	public void setOrganizationRepository(OrganizationRepository organizationRepository) {
		this.organizationRepository = organizationRepository;
	}
	
	@Override
	@Transactional
	public Organization findOne(String id) {
		Organization o = organizationRepository.findOne(id);
		return o;
	}
	
	@Override
	@Transactional
	public String addNew(Organization org,String parentId) throws Exception {
		Organization o = organizationRepository.findOne(org.getId());
		if(o!=null)throw BusinessException.DATA_DUPLICATION;
		if(parentId!=null){
			Organization parent = organizationRepository.findOne(parentId);
			org.setParent(parent);
		}
		organizationRepository.save(org);
		return org.getId();
	}
	
	@Override
	@Transactional
	public String update(Organization o) throws Exception {
		Organization org = organizationRepository.findOne(o.getOldId());
		if(org==null)throw BusinessException.DATA_NOT_FOUND;
		org.setLabel(o.getLabel());
		org.setActiveFlag(o.getActiveFlag());
		org.setCode(o.getCode());
		organizationRepository.save(org);
		return o.getOldId();
	}
	
	
	@Override
	@Transactional
	public String remove(String oId) {
		List<Organization> os=new ArrayList<Organization>();
		os=findTreeById(oId,os);
		organizationRepository.delete(os);
		return oId;
	}
	
	@Transactional
	private List<Organization> findTreeById(String id,List<Organization> os){
		Organization o=organizationRepository.findOne(id);
		os.add(o);
		Set<Organization> dvcs=o.getChildrens();
		if(dvcs!=null&&dvcs.size()!=0){
			for(Organization d:dvcs){
				findTreeById(d.getId(),os);
			}
		}
		return os;
	}
	
	@Override
	@Transactional
	public List<Organization> findAll() {
		return organizationRepository.findAll();
	}
	
}
